package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import util.DBUtilOfServlet;
import entity.Blog_User;

public class ImpUserDaoByServlet implements UserDao {
	private Connection conn = null;
	//根据user_id查询user信息
	@Override
	public Blog_User selectUserByUserId(String user_id) {
		Blog_User user = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = DBUtilOfServlet.getConnection();
		} catch (SQLException e) {
			System.out.println("获取数据库连接失败");
			e.printStackTrace();
		}
		String sql = "select * from blog_user where user_id = ?";
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, user_id);
			rs = ps.executeQuery();
			//判断是否有数据
			if(!rs.next()){
				return user;
			}
		} catch (SQLException e) {
			System.out.println("sql查询异常");
			e.printStackTrace();
		}
		List<Blog_User> list = new ArrayList<Blog_User>();
		try {
			list.add(createUser(rs));
			while(rs.next()){
				list.add(createUser(rs));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		try {
			if(rs != null){
				rs.close();
			}
			if(ps != null){
				ps.close();
			}
			if(conn != null){
				//conn.close();
				DBUtilOfServlet.close(conn);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		//int size = list.size();
		//System.out.println("数据条数："+list.size());
		System.out.println("用户信息为："+list.get(0).toString());
		return list.get(0);
	}
	//插入user信息
	@Override
	public int addUser(Blog_User user) {
		try {
			conn = DBUtilOfServlet.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		String sql = "insert into blog_user values(null,?,?,null,?,?,'1','3')"; 
		PreparedStatement ps = null;
		int rows = 0 ;
		try {
			ps = conn.prepareStatement(sql);
			ps.setString(1, user.getUser_id());
			ps.setString(2, user.getUser_password());
			ps.setString(3, user.getUser_phone());
			ps.setString(4, user.getUser_email());
			rows = ps.executeUpdate();
		} catch (SQLException e) {
			System.out.println("注册sql异常");
			e.printStackTrace();
		}
		try {
			if(ps != null){
				ps.close();
			}
			if(conn != null){
			    DBUtilOfServlet.close(conn);
				//conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rows;
	}
	//结果集创建返回一个user对象(工具)
	private Blog_User createUser(ResultSet rs) throws SQLException{
		Blog_User user = new Blog_User();
		user.setUser_num(rs.getInt("user_num"));
		user.setUser_nickname(rs.getString("user_nickname"));
		user.setUser_phone(rs.getString("user_phone"));
		user.setUser_email(rs.getString("user_email"));
		user.setUser_id(rs.getString("user_id"));
		user.setUser_password(rs.getString("user_password"));
		user.setUser_state(rs.getString("user_state"));
		user.setUser_type(rs.getString("user_type"));
		return user;
	}
	
}
